package top.kpromise.user.controller;

import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.kpromise.user.data.Config;
import top.kpromise.user.model.response.UserLoginModel;
import top.kpromise.user.model.response.UserModel;
import top.kpromise.user.response.Result;
import top.kpromise.user.service.UserLoginService;
import top.kpromise.user.service.UserService;
import top.kpromise.user.utils.KongUtils;
import top.kpromise.user.utils.RegularUtils;
import top.kpromise.user.utils.SecurityUtils;

import java.util.Map;

@RestController
@RequestMapping("/user/login")
public class UserLoginController {

    private final UserService userService;
    private final UserLoginService userLoginService;
    private final KongUtils kongUtils;

    public UserLoginController(UserService userService, UserLoginService userLoginService, KongUtils kongUtils) {
        this.userService = userService;
        this.kongUtils = kongUtils;
        this.userLoginService = userLoginService;
    }

    @RequestMapping("/password")
    public Map<String, Object> loginWithPassword(String loginValue, String password, @RequestHeader("appId") String appId) {
        UserModel userModel;
        if (RegularUtils.isEmail(loginValue)) {
            userModel = userService.findUserByEmail(loginValue);
            if (userModel == null) {
                return Result.error("该邮箱尚未注册");
            }
        } else {
            String phone = RegularUtils.formatPhone(loginValue);
            if (phone == null) {
                return Result.error("手机号格式错误");
            }
            userModel = userService.findUserByPhone(phone);
            if (userModel == null) {
                return Result.error("该手机号尚未注册");
            }
        }
        if (userModel.getEnabled() != 1) {
            return Result.error("用户已禁用，请联系客服");
        }
        UserLoginModel userLoginModel = userLoginService.findUser(userModel.getId(), Config.LoginType.PASSWORD);
        if (userLoginModel == null) {
            return Result.error("登录异常，请联系客服");
        }
        if (userLoginModel.getEnabled() != 1) {
            return Result.error("密码登录已禁用");
        }
        if (!userLoginModel.getLoginValue().equals(SecurityUtils.md5(password, Config.PASSWORD_SALT))) {
            return Result.error("密码错误");
        }
        return kongUtils.loginToKong(appId, userModel.getId());
    }

    @RequestMapping("/logout")
    public Map<String, Object> logout(@RequestHeader("appId") String appId, @RequestHeader("userId") String userId) {
        kongUtils.logout(appId, userId);
        return Result.data(null, "退出登录成功");
    }

    @RequestMapping("/refreshToken")
    public Map<String, Object> refreshToken(String refreshToken, @RequestHeader("appId") String appId) {
        return kongUtils.refreshToken(appId, refreshToken);
    }
}
